package com.efounder.chat.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.core.xml.StubObject;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.MessageEvent;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.router.constant.RouterConstant;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.CommonUtils;
import com.efounder.utils.ResStringUtil;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 新版用户详情界面 （仿twitter 新浪微博）
 *
 * @author yqs 2018/05/10
 */
@Route(path = RouterConstant.CHAT_USERINFO_ACTIVITY)
public class JFUserInfoActivity extends BaseActivity {
    private static final int PERCENTAGE_TO_SHOW_IMAGE = 20;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private Toolbar toolbar;
    private int mMaxScrollSize;
    private String[] titles = new String[]{ResStringUtil.getString(R.string.chat_animal), ResStringUtil.getString(R.string.chat_reply), ResStringUtil.getString(R.string.chat_like)};
    private boolean mIsImageHidden;
    private ImageView avatarView;
    private LinearLayout middleArea;
    private ImageView iv_sex;//性别
    private TextView userNameView;//用户昵称
    private LinearLayout llRightButton;//右上角button
    private ImageView ivLeft;//右上角button图标
    private TextView tvFunction1;//右上角button文字
    private TextView tvSign;//签名
    private Button butSend;//发送按钮
    private LinearLayout llDoubleLayout;
    private Button butSendmessage;
    private Button butAdd;
    private RelativeLayout llBottom;

    private int groupId = -1;


    private User user;
    private int userId;
    //是否是好友
    private boolean isFriend = true;
    //是否是展示的群组成员
    private boolean isGroupUser = false;
    private SmartRefreshLayout refreshLayout;
    //是否正在刷新
    private boolean isRefresh = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /** 设置状态栏颜色 */
        // initSystemBarTint();
        setContentView(R.layout.wechatview_activity_jf_userinfo_old1);
        initView();

        initIntentData();
        //initData();
        //initTabLayout();
        initNetWorkData();
    }

    private void initIntentData() {
        if (getIntent().hasExtra("stubObject")) {
            //点击消息跳过来
            StubObject stubObject = (StubObject) getIntent().getSerializableExtra("stubObject");
            IMStruct002 imStruct002 = (IMStruct002) stubObject.getStubTable().get("imStruct002");
            String message = imStruct002.getMessage();
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(message);
                userId = jsonObject.optInt("id");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            userId = getIntent().getIntExtra("id", 1);
            groupId = getIntent().getIntExtra("groupId", -1);

        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            OpenEthRequest.cannelRequest();
            refreshLayout.finishRefresh(100);
        }
    }


    private void initView() {
        // tabLayout = (TabLayout) findViewById(R.id.tablayout);
        // viewPager = (ViewPager) findViewById(R.id.viewPager);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        avatarView = (ImageView) findViewById(R.id.iv_avatar);
        middleArea = (LinearLayout) this.findViewById(R.id.middle_remark);
        iv_sex = (ImageView) findViewById(R.id.iv_sex);
        llRightButton = (LinearLayout) findViewById(R.id.ll_right_button);
        ivLeft = (ImageView) findViewById(R.id.iv_left);
        tvFunction1 = (TextView) findViewById(R.id.tv_function1);
        tvSign = (TextView) findViewById(R.id.tv_sign);
        butSend = (Button) findViewById(R.id.but_send);
        userNameView = (TextView) findViewById(R.id.tv_nickname);
        llDoubleLayout = (LinearLayout) findViewById(R.id.ll_double_layout);
        butSendmessage = (Button) findViewById(R.id.but_sendmessage);
        butAdd = (Button) findViewById(R.id.but_add);
        llBottom = (RelativeLayout) findViewById(R.id.ll_bottom);

        setSupportActionBar(toolbar);
        androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //左边的小箭头（注意需要在setSupportActionBar(toolbar)之后才有效果）
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(true);
            //设置返回键可用
            getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        }
        AppBarLayout appbar = (AppBarLayout) findViewById(R.id.appbar);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                isRefresh = true;
                initNetWorkData();
            }
        });
        //沉浸式状态栏
        if(immersionBarEnabled()){
            ImmersionBar.setTitleBar(this,toolbar);
        }
    }

    private void initListener() {

        //返回按钮点击
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //头像
        avatarView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (user.getAvatar() != null && user.getAvatar().contains("http")) {
                    Intent intent = new Intent(JFUserInfoActivity.this,
                            ShowBigImageActivity.class);
                    intent.putExtra("path", user.getAvatar());
                    ActivityOptionsCompat options = ActivityOptionsCompat
                            .makeSceneTransitionAnimation(JFUserInfoActivity.this, avatarView, "avatar");
                    ActivityCompat.startActivity(JFUserInfoActivity.this, intent, options.toBundle());
                } else {
                    ToastUtil.showToast(JFUserInfoActivity.this, R.string.chat_user_not_set_head);
                }
            }
        });
        //发送消息按钮
        butSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isFriend) {
                    //不是好友 添加好友
                    if (Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) == userId) {
                        Toast.makeText(JFUserInfoActivity.this, R.string.chat_not_add_mine_friend, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    //searchUser(userId);
                    AddUserOrGroupVerifyActivity.start(JFUserInfoActivity.this, userId, StructFactory.TO_USER_TYPE_PERSONAL);
                    return;
                }

                EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(userId));
                Intent intent = new Intent();
                intent.putExtra("id", userId);
                intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
                ChatActivitySkipUtil.startChatActivity(JFUserInfoActivity.this, intent);
                finish();
            }
        });
        //右上角按钮
        final int loginUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));
        //是否显示空间
        if (!"0".equals(EnvironmentVariable.getProperty("isShowMyZone"))) {
            llRightButton.setVisibility(View.VISIBLE);
        } else {
            llRightButton.setVisibility(View.INVISIBLE);
        }


        llRightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Bundle bundle = new Bundle();
                    bundle.putInt("other_user_id", user.getId());
                    bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, true);
                    EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("com.efounder.zone.fragment.MainZoneFragment"), bundle);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
        });
        butAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                searchUser(userId);
                AddUserOrGroupVerifyActivity.start(JFUserInfoActivity.this, userId, StructFactory.TO_USER_TYPE_PERSONAL);
            }
        });

        butSendmessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EnvironmentVariable.setProperty("currentChatUserId", String.valueOf(userId));
                Intent intent = new Intent();
                intent.putExtra("id", userId);
                intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
                ChatActivitySkipUtil.startChatActivity(JFUserInfoActivity.this, intent);
                finish();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
//        user = WeChatDBManager.getInstance().getOneFriendById(userId);
//        if (!user.isExist()) {
//            butSend.setText("添加好友");
//            isFriend = false;
//            user = WeChatDBManager.getInstance().getOneUserById(userId);
//        } else {
//            isFriend = true;
//            butSend.setText("发送消息");
//        }
//        if (isGroupUser) {
//            user = GroupNameUtil.getGroupUser(groupId, userId, WeChatDBManager.getInstance());
//            user.setReMark(GroupNameUtil.getGroupUserName(user));
//        }
//        // 设置用户名
//        userNameView.setText(user.getReMark());
//        initListener();
//        refreshButtonDisPay();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }

    private void initData() {
        if (groupId != -1) {
            isGroupUser = true;
        }

        user = WeChatDBManager.getInstance().getOneFriendById(userId);
        if (!user.isExist()) {
            butSend.setText(R.string.chat_add_friend);
            isFriend = false;
            user = WeChatDBManager.getInstance().getOneUserById(userId);
        } else {
            isFriend = true;
            butSend.setText(R.string.chat_send_message);
        }

        if (isGroupUser) {
            user = GroupNameUtil.getGroupUser(groupId, userId);
            user.setReMark(GroupNameUtil.getGroupUserName(user));
        }

        // 设置用户名
        userNameView.setText(user.getReMark());
        initListener();
        refreshButtonDisPay();
//        if (!isFriend) {
//            ivLeft.setImageDrawable(getResources().getDrawable(R.drawable.wechatview_userino_addfriend));
//            tvFunction1.setText("添加好友");
//        } else {
//            ivLeft.setImageDrawable(getResources().getDrawable(R.drawable.wechatview_userinfo_alternickname));
//            if (isGroupUser) {
//                tvFunction1.setText("设置群昵称");
//            } else {
//                tvFunction1.setText("修改备注");
//            }
//        }
        setcontent(user);

    }

    //刷新按钮的显示
    private void refreshButtonDisPay() {
        //显示的如果是群成员 如果允许陌生人聊天并且不是好友，显示两个按钮
        if (//isGroupUser &&
                !isFriend && user.isAllowStrangerChat()
                        && Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)) != userId
                        && EnvSupportManager.isSupportSetStrangerChat()) {
            llDoubleLayout.setVisibility(View.VISIBLE);
            llBottom.setVisibility(View.GONE);
        } else {
            llDoubleLayout.setVisibility(View.GONE);
            llBottom.setVisibility(View.VISIBLE);
        }
    }


//    private void initTabLayout() {
//        viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), titles));
//        for (int i = 0; i < titles.length; i++) {
//            tabLayout.addTab(tabLayout.newTab().setText(titles[i]));
//        }
//        tabLayout.setupWithViewPager(viewPager);
//        tabLayout.getTabAt(0).select();
//    }
//
//    @Override
//    protected boolean translucentStatusBar() {
//        return true;
//    }
//
//
//    private class MyPagerAdapter extends FragmentPagerAdapter {
//
//        private String[] titles;
//
//        public MyPagerAdapter(FragmentManager fm, String[] titles) {
//            super(fm);
//            this.titles = titles;
//        }
//
//        @Override
//        public Fragment getItem(int position) {
//
//            return new ChatUserDynamicListFragment();
//
//        }
//
//        @Override
//        public int getCount() {
//            return titles.length;
//        }
//
//        @Nullable
//        @Override
//        public CharSequence getPageTitle(int position) {
//            return titles[position];
//        }
//    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_jf_userinfo_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (isFriend) {
            menu.findItem(R.id.delete_friend).setVisible(true);
            menu.findItem(R.id.set_remark).setVisible(true);
            menu.findItem(R.id.share_name_card).setVisible(true);

        } else {
            menu.findItem(R.id.delete_friend).setVisible(false);
            menu.findItem(R.id.set_remark).setVisible(false);
            menu.findItem(R.id.share_name_card).setVisible(false);
        }
        if (isGroupUser) {
            menu.findItem(R.id.set_remark).setVisible(true);
        } else {
            menu.findItem(R.id.set_remark).setTitle(ResStringUtil.getString(R.string.chat_update_remark));
        }
        final int loginUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));
        if (loginUserId == userId) {
            menu.findItem(R.id.delete_friend).setVisible(false);
            menu.findItem(R.id.set_remark).setVisible(false);
        }
        //反射显示菜单图标
        if (menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                    Log.e(getClass().getSimpleName(), "onMenuOpened...unable to set icons for overflow menu", e);
                }
            }
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.delete_friend) {
            deleteFriend();
            return true;
        } else if (id == R.id.set_remark) {
            Intent intent = new Intent(JFUserInfoActivity.this, UserRemarkActivity.class);
            intent.putExtra("id", userId);
            if (isGroupUser) {
                intent.putExtra("groupId", groupId);
            }
            startActivity(intent);
        } else if (id == R.id.set_remark) {
            Intent intent = new Intent(JFUserInfoActivity.this, UserRemarkActivity.class);
            intent.putExtra("id", userId);
            if (isGroupUser) {
                intent.putExtra("groupId", groupId);
            }
            startActivity(intent);
        } else if (id == R.id.share_name_card) {
            //分享给好友
            Intent intent = new Intent(JFUserInfoActivity.this, ShareNameCardActivity.class);
            intent.putExtra("id", userId);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    private void deleteFriend() {
        AlertDialog dialog = new AlertDialog.Builder(JFUserInfoActivity.this).
                setMessage(ResStringUtil.getString(R.string.chat_sure_delete_friend)).setTitle(R.string.common_text_hint).setNegativeButton(R.string.common_text_cancel, null)

                .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        showLoading(ResStringUtil.getString(R.string.chat_deleteing));
                        GetHttpUtil.deleteFriend(JFUserInfoActivity.this, userId, new
                                GetHttpUtil.UpdateUserInfoCallBack() {


                                    @Override
                                    public void updateSuccess(boolean isSuccess) {
                                        if (isSuccess) {
                                            dismissLoading();
                                            clearBadgem(userId, StructFactory.TO_USER_TYPE_PERSONAL);

                                            //跳转到首页
                                            if (!isGroupUser) {
                                                try {
                                                    ToastUtil.showToast(JFUserInfoActivity.this,
                                                            R.string.chat_delete_friend_success);
                                                    String className = getResources().getString(R.string.from_group_backto_first);
                                                    Class clazz = Class.forName(className);
                                                    Intent myIntent = new Intent
                                                            (JFUserInfoActivity.this, clazz);
                                                    startActivity(myIntent);
                                                } catch (ClassNotFoundException e) {
                                                    e.printStackTrace();
                                                }


                                                JFUserInfoActivity.this.finish();
                                            } else {
                                                Intent intent = getIntent().putExtra("delete", 1);
                                                setResult(1, intent);
                                                JFUserInfoActivity.this.finish();
                                            }

                                        } else {
                                            dismissLoading();
                                            ToastUtil.showToast(JFUserInfoActivity.this,
                                                    R.string.chat_delete_friend_fail);
                                        }
                                    }
                                });
                        dialogInterface.dismiss();
                    }
                }).show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.title_Background));
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.title_Background));

    }

    /**
     * 设置内容
     *
     * @param user
     */
    private void setcontent(final User user) {

        Map<String, String> map = new LinkedHashMap<String, String>();
        String key1 = getResources().getString(R.string.showNumberText);
        map.put(key1, String.valueOf(user.getId()));
        if (EnvironmentVariable.getProperty("isShowWalletAddress", "0").equals("1")) {
            map.put(ResStringUtil.getString(R.string.chat_base_id), user.getWalletAddress());
        } else {
            //todo 不是星际通讯的话就显示帐号 yqs 20190427
            String key2 = getResources().getString(R.string.chat_number);
            map.put(key2, String.valueOf(user.getName()));
        }
        user.setRemarkmap(map);
        middleArea.removeAllViews();
        //设置个性签名
        if (user.getSigNature() == null || user.getSigNature().equals("")) {
            tvSign.setText(R.string.chat_unfilled);
        } else {
            tvSign.setText(user.getSigNature());

        }
        if (isFinishing() || isDestroyed()) {
            return;
        }
        LXGlideImageLoader.getInstance().showRoundUserAvatar(this, avatarView, user.getAvatar(), 100);
        userNameView.setText(user.getReMark());


        // 设置性别
        String sex = user.getSex();

        if ("M".equals(sex)) {
            iv_sex.setImageResource(R.drawable.ic_sex_male);
        } else if ("F".equals(sex)) {
            iv_sex.setImageResource(R.drawable.ic_sex_female);
        } else {
            iv_sex.setVisibility(View.GONE);
        }

        // 设置描述区域
        final Map<String, String> remarkMap = user.getRemarkmap();

        LayoutInflater inflater = LayoutInflater.from(this);
        for (final String key : remarkMap.keySet()) {
            System.out.println("key= " + key + " and value= "
                    + remarkMap.get(key));
            ViewGroup userinfo_merge = (ViewGroup) inflater.inflate(
                    R.layout.userinfo_merge, null);
            TextView merge_key = (TextView) userinfo_merge
                    .findViewById(R.id.merge_key);
            merge_key.setText(key);

            TextView merge_value = (TextView) userinfo_merge
                    .findViewById(R.id.merge_value);
            merge_value.setText(remarkMap.get(key));
            ImageView ivCopyAddress = (ImageView) userinfo_merge.findViewById(R.id.iv_copy_address);

            if (key.equals(ResStringUtil.getString(R.string.chat_base_id))) {
//                merge_value.setEllipsize(TextUtils.TruncateAt.MIDDLE);
//                merge_value.setMaxLines(1);
                ivCopyAddress.setVisibility(View.VISIBLE);
                ivCopyAddress.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//                    // 将文本内容放到系统剪贴板里。
                        cm.setText(remarkMap.get(key));
                        ToastUtil.showToast(getApplicationContext(), R.string.chat_copy_to_clipboard);
                    }
                });
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, CommonUtils.dip2px(this, 48));
            middleArea.addView(userinfo_merge, lp);
        }

    }

    private void initNetWorkData() {
        //if (!user.isExist()) {
        GetHttpUtil.getUserInfo(userId, JFUserInfoActivity.this, new GetHttpUtil.GetUserListener() {
            @Override
            public void onGetUserSuccess(User user1) {
                //refreshLayout.finishRefresh(300);
                //user = WeChatDBManager.getInstance().getOneFriendById(user1.getId());
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    if (JFUserInfoActivity.this.isFinishing() || JFUserInfoActivity.this.isDestroyed()) {
                        return;
                    }
                }
                user = user1;
                //initData();
                getEthUserData();
            }

            @Override
            public void onGetUserFail() {
                if (isRefresh) {
                    ToastUtil.showToast(JFUserInfoActivity.this, ResStringUtil.getString(R.string.chat_get_info_fail_again));
                }
                isRefresh = false;
                refreshLayout.finishRefresh(100);
                getEthUserData();

            }
        });
//        } else {
//            getEthUserData();
//        }

    }

    public void getEthUserData() {
        //显示钱包地址
        if (EnvironmentVariable.getProperty("isShowWalletAddress", "0").equals("1")) {
            //&& user.getRSAPublicKey() == null) {

            OpenEthRequest.getUserEthByImUserId(JFUserInfoActivity.this, userId, new OpenEthRequest.EthUserRequestListener() {
                @Override
                public void onSuccess(User user1) {
                    user.setWalletAddress(user1.getWalletAddress());
                    user.setPublicKey(user1.getPublicKey());
                    user.setRSAPublicKey(user1.getRSAPublicKey());
                    user.setWeixinQrUrl(user1.getWeixinQrUrl());
                    user.setZhifubaoQrUrl(user1.getZhifubaoQrUrl());
                    WeChatDBManager.getInstance().insertUserTable(user);
                    initData();
                    refreshLayout.finishRefresh(200);
                    isRefresh = false;

                }

                @Override
                public void onSuccess(String ethAddress, String publicKey, String RSAPublicKey) {
//                    user.setWalletAddress(ethAddress);
//                    user.setPublicKey(publicKey);
//                    user.setRSAPublicKey(RSAPublicKey);
//                    WeChatDBManager.getInstance().insertUserTable(user);
//                    // setcontent(user);
//                    initData();
//                    refreshLayout.finishRefresh(200);
//                    isRefresh = false;

                }

                @Override
                public void onFail(String error) {
                    refreshLayout.finishRefresh(200);
                    if (isRefresh && !"".equals(error)) {
                        ToastUtil.showToast(JFUserInfoActivity.this, error + "");
                    }
                    if (ResStringUtil.getString(R.string.chat_user_not_exist).equals(error)) {
                        user.setWalletAddress(null);
                        user.setPublicKey(null);
                        user.setRSAPublicKey(null);
                        WeChatDBManager.getInstance().insertUserTable(user);
                        initData();
                    }

                    isRefresh = false;

                    //ToastUtil.showToast(JFUserInfoActivity.this, "获取用户信息失败，请重试");
                }
            }, true);


        } else {
            initData();
            refreshLayout.finishRefresh(200);
            isRefresh = false;
        }
    }

    private void clearBadgem(int id, byte chatType) {

        //清除当前聊天的角标
        ChatListItem chatListItem = WeChatDBManager.getInstance().getChatListItem(id, chatType);

        JFMessageManager.getInstance().unreadZero(id, chatType);
        int unReadCount = JFMessageManager.getInstance().
                getUnReadCount(id, chatType);
        if (unReadCount == 0) {
            unReadCount = -1;
        }
        if (chatListItem != null) {
            chatListItem.setBadgernum(unReadCount);
            WeChatDBManager.getInstance().deleteChatListiItem(chatListItem);

            EventBus.getDefault().post(new MessageEvent(chatListItem, MessageEvent.DELETE));

        }


    }

}